package org.compiere.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import javax.swing.JFileChooser;
import javax.swing.JList;

import org.compiere.util.DB;
import org.compiere.util.Env;

public class CalloutHRMPayment extends CalloutEngine {

	public String UploadSwift(Properties ctx, int WindowNo, GridTab mTab,
			GridField mField, Object value) {
		
		FileOutputStream fos = null;
		OutputStreamWriter out = null;
		
		try{
			final JFileChooser fc = new JFileChooser();
			fc.setApproveButtonText("Выбрать");//выбрать название для кнопки согласия
			fc.setDialogTitle("Выберите каталог для загрузки файла: Swift.txt");// выбрать название
			JList list = new JList();
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

			
			if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
				String FileName = fc.getSelectedFile().getAbsolutePath() + "/Swift.txt";
//				String FileName = "/home/alm/Documents/work/swift/swift.txt";
				File file = new File(FileName);//fc.getSelectedFile();
				fos = new FileOutputStream(file);
				out = new OutputStreamWriter(fos, "UTF8");//"CP866");
				
				int hrm_payment_ID = Env.getContextAsInt(ctx, WindowNo,
						"hrm_payment_ID");
				
				Mhrmpayment hrm_payment = new Mhrmpayment(ctx, hrm_payment_ID, null);
				
				String sql = " select hrm_payment_list_id from adempiere.hrm_payment_list where hrm_payment_ID = " + hrm_payment_ID;

				List<Mhrmpaymentlist> lines = new ArrayList<Mhrmpaymentlist>();
				Mhrmpaymentlist line;
				
				PreparedStatement pstmt = null;
				ResultSet rs = null;
					
				pstmt = null;
				rs = null;
				pstmt = DB.prepareStatement(sql, null);
				rs = pstmt.executeQuery();
				Timestamp ts;
				while (rs.next()) {
					line = new Mhrmpaymentlist(ctx, rs.getInt(1), null);
					lines.add(line);
				}

				//static	
				out.write("{1:F01KKOZKX0000000001000001}"); 	out.write("\r\n");
				out.write("{2:I102SGROSS000000U3003}"); out.write("\r\n");
				out.write("{4:"); 						out.write("\r\n");
				out.write(":20:111111211200673"); 		out.write("\r\n");
				out.write("/NAME/АКЦИОНЕРНОЕ ОБЩЕСТВО  "+'"'+"НАЦИОНАЛЬНЫЙ ИНФОКОММУНИКАЦИОННЫЙ ХОЛДИНГ "+'"'+"ЗЕРДЕ"+'"'); out.write("\r\n");				
				out.write("/RNN/620200331655"); 		out.write("\r\n");
				out.write("/CHIEF/КУРГАНБЕКОВА З. Е.");	out.write("\r\n");		//" + (director == null ? "" : director)); 
				out.write("/MAINBK/НУРАХМЕТОВА А. Т.");	out.write("\r\n");		// + (chiefAcc == null ? "" : chiefAcc)); 
				out.write("/IRS/1"); 					out.write("\r\n");
				out.write("/SECO/6"); 					out.write("\r\n");		
				out.write(":52B:KZKOKZKX");				out.write("\r\n");		// + (swift == null ? "" : swift )); 	//old BIK
				out.write(":57B:KZKOKZKX");				out.write("\r\n");		// + (accountNo3 == null ? "" : accountNo3)); out.write("\r\n");	//new BIK
				out.write(":59:KZ769260010810003398");	out.write("\r\n");		// + (accountNo2 == null ? "" : accountNo2)); 	//fix				
				out.write("/NAME/Казкоммерцбанк АО");	out.write("\r\n");		// + (name == null ? "" : name)); 
				out.write("/RNN/600400055239");			out.write("\r\n");		// + (rnn1 == null ? "" : rnn1)); 
				out.write("/IRS/1");					out.write("\r\n");		// + (resident2 == null ? "" : resident2));  
				out.write("/SECO/9");					out.write("\r\n");		// + (sector2 == null ? "" : sector2)); out.write("\r\n");
				out.write(":70:");						out.write("\r\n");
				out.write("/NUM/"+(hrm_payment.getDocumentNo() == null ? "" : hrm_payment.getDocumentNo())); out.write("\r\n");	
				
				String dateacct = hrm_payment.getDateFrom().toString();
				if(dateacct!=null) dateacct = dateacct.substring(2, 4) + dateacct.substring(5, 7) + dateacct.substring(8,10); 
				out.write("/DATE/"+(dateacct == null ? "" : dateacct)); out.write("\r\n");
				
				out.write("/VO/01"); 					out.write("\r\n");	//fix
				out.write("/SEND/07"); 					out.write("\r\n");	//fix
				out.write("/KNP/311");					out.write("\r\n");	// + (routingno == null ? "" : routingno)); out.write("\r\n");	//new BIK//(kpn == null ? "" : kpn)); out.write("\r\n");
//				out.write("/ASSIGN/" + (hrm_payment.getName() == null ? "" : hrm_payment.getName())); out.write("\r\n");
				
				int row = 1;
				for(Mhrmpaymentlist l: lines){
					out.write(":21:" + row); 				out.write("\r\n");
					
					String payment =  l.gethrm_amountsalary().toString();
					if(payment!=null || payment.equals("")){
						BigDecimal bg = new BigDecimal(payment).setScale(2,BigDecimal.ROUND_UP);
						payment = bg.toPlainString().replace(".", ",");
					} else payment = "0";
					
					out.write(":32B:KZT" + (payment == null ? "0" : payment)); out.write("\r\n");
					out.write(":70:");						out.write("\r\n");
					
					MBPartner  mbp = new MBPartner(ctx, l.getC_BPartner_ID(), null);
					out.write("/FM/" + (mbp.getFirstName() == null ? "" : mbp.getFirstName()));	out.write("\r\n");					
					out.write("/NM/" + (mbp.getLastName() == null ? "" : mbp.getLastName()));	out.write("\r\n");
					out.write("/FT/" + (mbp.getMiddleName() == null ? "" : mbp.getMiddleName()));	out.write("\r\n");
					out.write("/RNN/" + (mbp.getFI_TIN() == null ? "" : mbp.getFI_TIN()));	out.write("\r\n");
					
					
					MBPBankAccount[] ll = mbp.getBankAccounts(true);
					if(ll.length > 0){
						out.write("/LA/" + (ll[0].getAccountNo() == null ? "" : ll[0].getAccountNo()));	out.write("\r\n");
					}else{
						out.write("/LA/");	out.write("\r\n");
					}
					
					row++;	
				}

					// calc total amoumt
					String payment =  hrm_payment.gethrm_amountsalary().toString();
					if(payment!=null || payment.equals("")){
						BigDecimal bg = new BigDecimal(payment).setScale(2,BigDecimal.ROUND_UP);
						payment = bg.toPlainString().replace(".", ",");
					} else payment = "0";
					
				out.write(":32A:" + dateacct +  "KZT" + payment);	out.write("\r\n");
				out.write("-}");	out.write("\r\n");
				
				out.flush();
				out.close();
				fos.close();
			}
		}catch(Exception e){
			System.out.println(e.toString());
			return "HR.Payment.UploadSwift.Error:" + e.toString();
		}
		
		
		return "";
		
	}
		
}
